package SortAlgorithmPractice;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class RadixSort {
    public static void main(String[] args) {
        int[] arr = {3,1,5,6,9,7,8,10};
        System.out.printf("Sort before : %s\n", Arrays.toString(arr));
        radixSort(arr);
        System.out.printf("Sort after : %s\n", Arrays.toString(arr));
    }

    public static void radixSort(int[] arr){
        int max = Arrays.stream(arr).max().getAsInt();
        int maxDigit = String.valueOf(max).length();
        int mod = 10, div = 1;
        List<List<Integer>> buckets = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            buckets.add(new ArrayList<>());
        }
        for (int i = 0; i < maxDigit; i++, mod *= 10, div *= 10) {
            for (int num : arr) {
                int bucketIndex = (num % mod) / div;
                buckets.get(bucketIndex).add(num);
            }
            int index = 0;
            for (List<Integer> bucket : buckets) {
                for (int num : bucket) {
                    arr[index++] = num;
                }
                bucket.clear();
            }
        }
    }
}
